package dao;

import entity.Calendar;
import entity.IEntity;
import entity.Student;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Alexander
 */
public class CalendarDAO implements IDAO{

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Calendar)em.find(Calendar.class, (int) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Calendar cal = (Calendar)em.getReference(Calendar.class, (int) id);
        em.remove(cal);
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Calendar.class));
        Query q = em.createQuery(cq);
        return q.getResultList();  
    }
    
    /**
     * Busca el calendario de un alumno especifico
     * @param st Alumno que posee el calendario
     * @param em Administrador de transacciones
     * @return El calendario del usuario
     */
    public IEntity findByUser(Student st, EntityManager em){
        Query q = em.createQuery("SELECT c FROM Calendar "
                + "WHERE student = :alumno").setParameter("alumno", st);
        
        Calendar cl = null;
        
        try{
            cl = (Calendar) q.getSingleResult();
        }
        catch(NonUniqueResultException nex){
            cl = (Calendar) q.getResultList().get(0);
        }
        catch(NoResultException nrex){
            cl = null;
        }
        
        return cl;
    }   
}
